package server.bootstrap;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.HttpServlet;
import server.Mapper.ContextMapper;
import server.Mapper.HostMapper;
import server.process.RequestMapperProcessor;
import server.Mapper.WrapperMapper;
import server.StaticResourceUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Hugh
 * @Date: 2020/6/1
 */
public class Minicat40BootStrap extends BaseBootStrap {

    private ThreadPoolExecutor threadPoolExecutor;

    private HostMapper hostMapper;


    /**
     * 开发Minicat V4.0，在已有Minicat基础上进⼀步扩展，模拟出webapps部署效果
     * 磁盘上放置⼀个webapps⽬录，webapps中可以有多个项⽬，⽐如demo1,demo2,demo3...
     * 具体的项⽬⽐如demo1中有serlvet（也即为：servlet是属于具体某⼀个项⽬的servlet），
     * 这样的话在 Minicat初始化配置加载，以及根据请求url查找对应serlvet时都需要进⼀步处理
     * @param socket socket
     * @throws Exception
     */
    @Override
    protected void doHandle(Socket socket) throws Exception {
        //也需要从新写 todo
        RequestMapperProcessor requestProcessor = new RequestMapperProcessor(socket,hostMapper);
        //requestProcessor.start();
        threadPoolExecutor.execute(requestProcessor);
    }

    @Override
    protected void init() throws Exception {
        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
    }

    @Override
    protected void loadServlet() throws Exception {
        loadWebappsServlet();
    }

    private void loadWebappsServlet(){
        //通过server.xml获取配置的端口号和webapp所在的目录
        //加载webapp所在的Servlet
        loadServerConfig();
    }

    private void loadServerConfig(){

        hostMapper = new HostMapper();
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//service");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <connector port="8090"/>
                Element portElement = (Element) element.selectSingleNode("connector");
                String port = portElement.attribute("port").getValue();
                // <engin>
                // <host name="localhost" appBase="/webapps"/>
                // </engin>
                Element servletclassElement = (Element) element.selectSingleNode("engin");
                Element hostElement = (Element)servletclassElement.selectNodes("host").get(0);
                String host = hostElement.attribute("name").getValue();
                String appBase = hostElement.attribute("appBase").getValue();

                //根据appBase加载指定目录下的类文件
                ContextMapper contextMapper = loadContextMapper(appBase);
                hostMapper.setHostMapper(host + ":" + port, contextMapper);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载ContextMapper
     * @param path path
     * @return ContextMapper
     * @throws FileNotFoundException FileNotFoundException
     */
    private ContextMapper loadContextMapper(String path) throws FileNotFoundException {
        ContextMapper contextMapper = new ContextMapper();
        //获取资源的绝对路径
        String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(path);
        //获取文件
        File[] projectsFile = new File(absoluteResourcePath).listFiles();
        for(File file : projectsFile){
            if(file.exists() && file.isDirectory()){
                String projectName = file.getName();
                File[] projectFile = file.listFiles();
                for(File childFile : projectFile){
                    if(childFile.isFile() && "web.xml".equals(childFile.getName())){
                        WrapperMapper wrapperMapper = loadProjectServlet(new FileInputStream(childFile));
                        contextMapper.setContextMapper(projectName, wrapperMapper);
                    }
                }
                System.out.println(projectName);
            }
        }

        return contextMapper;
    }

    /**
     *  从InputStream加载HttpServlet
     *
     * @param resourceAsStream InputStream
     * @return Map<String, HttpServlet>
     */
    private WrapperMapper loadProjectServlet(InputStream resourceAsStream){
        WrapperMapper wrapperMapper = new WrapperMapper();
        Map<String, HttpServlet> servletMap = new HashMap<String,HttpServlet>();

        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }
            wrapperMapper.setStringHttpServletMap(servletMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wrapperMapper;
    }
}
